package com.example.blog_springboot.controller;

import com.example.blog_springboot.config.NullException;
import com.example.blog_springboot.config.RepeatException;
import com.example.blog_springboot.model.User;
import com.example.blog_springboot.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/login")
    public void login(String username, String password, HttpServletRequest request) throws Exception {
        if(username==null||username.equals("")||password==null||password.equals("")){
            throw new NullException();
        }
        userService.login(username,password,request);
    }

    @PostMapping("/reg")
    public void reg(String username, String password) throws RepeatException {
        userService.add(username,password);
    }

    @GetMapping("/logout")
    public void logout(HttpServletRequest request) throws Exception {
        userService.logout(request);
    }

    @GetMapping("/getUser")
    public User getUser(@SessionAttribute("user")User user) {
        return user;
    }

    @GetMapping("/getWriter")
    public User getWriter(String blogId,@SessionAttribute("user")User user) throws Exception {
        if(blogId==null||blogId.equals("")){
            throw new Exception();
        }
        User writer = userService.getWriter(blogId,user);
        return writer;
    }
}